package com.ubxtech.core.utils;

import org.springframework.util.StringUtils;

/**
 * @author Victor.Xiao
 * @since 2022-09-08 15:34
 **/
public class HexStringUtil {

    /**
     * 将hex字符串转换成字节数组
     * @author xiaozhongsheng
     * @date 2021-07-01 17:46
     * @param hexString hexString
     * @return byte[]
     */
    public static byte[] hexStrToByteArr(String hexString) {
        if (!StringUtils.hasText(hexString)) {
            return new byte[]{};
        }
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;
        byte[] bytes = new byte[len / 2];

        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
            index += 2;
        }

        return bytes;
    }


    /**
     * 数组转换成十六进制字符串
     *
     * @return HexString
     */
    public static  String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
}
